<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="物料号" prop="itemCode">
        <el-select
          v-model="queryParams.itemCode"
          placeholder="请选择物料号"
          clearable
          @change="handleQuery"
          class="!w-240px"
          :loading="loading"
        >
          <el-option
            v-for="item in itemOptions"
            :key="item.itemCode"
            :label="item.itemCode"
            :value="item.itemCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="入库时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          v-if="props.type != 'selectMaterial'"
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['opticore:material-inventor:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      highlight-current-row
      :show-overflow-tooltip="true"
    >
      <el-table-column label="编号" align="center" prop="id" v-if="false" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="序列号" align="center" prop="serialNo" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="工单号" align="center" prop="docNo" />
      <el-table-column label="物料号" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="物料类型" align="center" prop="materialType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OPTICORE_MATE_TYPE" :value="scope.row.materialType" />
        </template>
      </el-table-column>
      <el-table-column label="物料单位" align="center" prop="unit" />
      <el-table-column label="物料规格" align="center" prop="itemSpecification" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="长度" align="center" prop="qty" />
      <el-table-column label="物料图号" align="center" prop="drawingNo" />
      <el-table-column label="位置" align="center" prop="location" />

      <el-table-column
        label="入库时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            v-if="props.type == 'selectMaterial'"
            link
            type="primary"
            v-hasPermi="['opticore:material-inventor:update']"
          >
            <el-checkbox
              v-model="scope.row.selItem"
              label=""
              size="large"
              @change="handleStockOut(scope.row)"
            />
          </el-button>

          <el-button
            v-else
            link
            type="primary"
            @click="openForm('query', scope.row)"
            v-hasPermi="['opticore:material-inventor:query']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialInventorform ref="formRef" @success="getList" />

  <!-- 出库对话框 -->

  <el-dialog v-model="stockOutDialogVisible" title="出库操作" width="400px">
    <el-form>
      <el-form-item label="物料号">
        <span>{{ currentStockRow?.itemCode }}</span>
      </el-form-item>
      <el-form-item label="物料名称">
        <span>{{ currentStockRow?.itemName }}</span>
      </el-form-item>
      <el-form-item label="出库数量" required>
        <el-input-number
          v-model="stockOutQty"
          :min="1"
          :max="currentStockRow?.qty || 0"
          :controls="false"
          placeholder="请输入出库数量"
        />
      </el-form-item>
      <el-form-item label="出库位置">
        <el-input v-model="stockOutLocation" placeholder="请输入出库位置" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="stockOutDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmStockOut()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MaterialInventorApi, MaterialInventorVO } from '@/api/opticore/materialinventor'
import MaterialInventorform from './MaterialInventorForm.vue'
import { WorkOrderCpsApi } from '@/api/opticore/workorder'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";

/** 中间库 列表 */
defineOptions({ name: 'MaterialInventor' })

const props = defineProps(['type', 'serialNo', 'itemCode', 'selmaxNum', 'docNo'])
const emits = defineEmits(['selectItem'])

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MaterialInventorVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: undefined,
  batchNo: undefined,
  docNo: undefined,
  itemCode: undefined,
  itemName: undefined,
  itemSpecification: undefined,
  itemDesc: undefined,
  drawingNo: undefined,
  unit: undefined,
  materialType: undefined,
  brand: undefined,
  qty: undefined,
  location: undefined,
  mainImage: undefined,
  status: undefined,
  createTime: [],
  minQty: undefined,
  maxQty: undefined
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const stockOutDialogVisible = ref(false)
const stockOutQty = ref()
const stockOutLocation = ref()
const currentStockRow = ref<any>(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if (props.type == 'selectMaterial') {
      queryParams.status = 0
    } else {
      queryParams.status = undefined
    }
    const data = await MaterialInventorApi.getMaterialInventorPage(queryParams)

    // 处理选中状态 - 多选逻辑
    data.list = data.list.map((item) => {
      // 检查当前序列号是否在选中的序列号列表中
      const isSelected = serialNoOptions.value.some(
        (selected: any) => selected.serialNo === item.serialNo
      )

      return {
        ...item,
        selItem: isSelected,
        isAbled: true // 允许多选，不再限制数量
      }
    })

    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.minQty > queryParams.maxQty) {
    message.info('物料最大长度不能小于最小长度')
    queryParams.maxQty = undefined
    return
  }
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.maxQty = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MaterialInventorApi.deleteMaterialInventor(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MaterialInventorApi.exportMaterialInventor(queryParams)
    download.excel(data, '物料追溯.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleStockOut = (row: any) => {
  list.value = list.value.map((item) => {
    if (item.id == row.id) {
      // 切换选中状态
      return {
        ...item,
        selItem: item.selItem // 取反当前选中状态
      }
    }
    return {
      ...item,
      selItem: false // 保持单选特性，其他行取消选中
    }
  })

  // 根据当前选中状态传递参数
  if (row.selItem) {
    emits('selectItem', row)
  } else {
    emits('selectItem', null) // 取消选中时传递null
  }
}

const confirmStockOut = async () => {
  // 这里调用出库接口，传递 currentStockRow.value.id 和 stockOutQty.value

  // await MaterialInventorApi.updateMaterialInventor({ id: currentStockRow.value.id, qty: stockOutQty.value })
  // 1. 校验出库数量不能为空且为正整数
  if (!stockOutQty.value && stockOutQty.value <= 0) {
    message.error('出库数量必须大于0')
    return
  }
  // 2. 校验出库数量不能大于现有库存
  if (stockOutQty.value > currentStockRow.value.qty) {
    message.error('出库数量不能大于现有库存数量')
    return
  }

  const params = {
    ...currentStockRow.value,
    qty: currentStockRow.value.qty - stockOutQty.value, // 更新后的数量
    location: stockOutLocation.value
  }
  await MaterialInventorApi.updateMaterialInventor(params)
  console.log(stockOutQty.value)
  message.success('出库成功')

  stockOutDialogVisible.value = false
  getList()
}

// 物料选项数据
const itemOptions = ref([])
// 获取物料列表的函数
const fetchItemOptions = async () => {
  if (!props.docNo) return
  try {
    itemOptions.value = await WorkOrderCpsApi.getWorkOrderBomPlcListByDocNoAndType(props.docNo) || []
    if (itemOptions.value.length > 0) {
      queryParams.itemCode = itemOptions.value[0].itemCode
    }
  } catch (error) {
    ElMessage.error('获取物料列表失败')
  }
}

// 工单选中的物料序列号
const serialNoOptions = ref([])
// 获取物料列表的函数
const fetchSerialNoOptions = async () => {
  if (!props.docNo) return
  try {
    serialNoOptions.value = await MaterialInventorApi.getOrderNodeDetailMaterialByDocNo(props.docNo) || [];
  } catch (error) {
    ElMessage.error('获取物料列表失败')
  }
}

/** 初始化 **/
onMounted(() => {
  // 先获取选中的序列号列表，再加载数据列表
  fetchSerialNoOptions().then(() => {
    fetchItemOptions().then(() => {
      setTimeout(() => {
        getList()
        // 初始化时发送已选中的项目给父组件
        const selectedItems = list.value.filter(item => item.selItem)
        emits('selectItem', selectedItems)
      }, 200)
    })
  })
})

watch(
  props, //监听选择来料的品号发生变化
  (val,old) => {
    fetchSerialNoOptions().then(() => {
      fetchItemOptions().then(() => {
        setTimeout(() => {
          getList()
          // props变化时发送已选中的项目给父组件
          const selectedItems = list.value.filter(item => item.selItem)
          emits('selectItem', selectedItems)
        }, 200)
      })
    })
  }
)
</script>
